package com.rupertjones.globalcron.web;

import com.rupertjones.globalcron.domain.Setting;
import com.rupertjones.globalcron.domain.SettingType;
import com.rupertjones.globalcron.domain.User;
import com.rupertjones.globalcron.web.service.SettingsService;
import com.rupertjones.globalcron.web.service.DefaultUserService;
import com.rupertjones.globalcron.web.service.UserService;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrors;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * <p>&copy Rupert Jones 2011,2012</p>
 *
 * @author rup
 */
public class ProfileAction extends AbstractFormAction {

    @ValidateNestedProperties({
            @Validate(field = "password", required = true, on = { "SaveOrUpdate" }),
            @Validate(field = "fullName", required = true, on = { "SaveOrUpdate" })
    })
    private FormUser formUser;

    private User actualUser;

    private String sessionUser;

    @SpringBean
    private UserService userService;

    @SpringBean
    private SettingsService settingsService;

    private Setting passwordPolicy;

    @Before(stages = LifecycleStage.BindingAndValidation)
    public void loadAndBind() {
        sessionUser = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        actualUser = getUserService().findUser(sessionUser);
        passwordPolicy = settingsService.find(SettingType.PASSWORD_POLICY);
        formUser = new FormUser(passwordPolicy);
        formUser.setFullName(actualUser.getFullName());
    }

    @DefaultHandler
    public Resolution view() {
        return new ForwardResolution("/WEB-INF/jsp/profile.jsp");
    }

    @HandlesEvent("SaveOrUpdate")
    public Resolution onSave() {
        User user = userService.findUser(sessionUser);

        boolean passwordMatch = this.formUser.isPasswordMatch();
        boolean compliant = this.formUser.isPasswordPolicyCompliant();
        ValidationErrors errors = new ValidationErrors();

        if(!passwordMatch) {
            errors.add("password", new LocalizableError("password.nomatch"));
        }

        if(!compliant) {
            errors.add("password", new SimpleError(passwordPolicy.getDescription()));
        }

        if (errors.size() == 0) {
            user.setFullName(this.formUser.getFullName());
            userService.saveWithPassword(user, this.formUser.getPassword());
            return new ForwardResolution("Home.action");
        } else {
            getContext().setValidationErrors(errors);
            return getContext().getSourcePageResolution();
        }
    }

    public FormUser getUser() {
        return formUser;
    }
}
